package com.wlient.basic.Thread.Quene;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * @author: 史炜立
 * @description: TODO
 * @date: 2021/12/15 13:38
 */
public class ArrayBlockingQueueDemo {
    private ArrayBlockingQueue<Url> blockingQueue;
    // 消费者线程
    private IndexingThread indexingThread;

    //无参构造，一开始就开启消费者线程
    public ArrayBlockingQueueDemo() {
        // 容量为200的任务队列
        blockingQueue = new ArrayBlockingQueue<>(200);
        indexingThread = new IndexingThread(blockingQueue);
        // 启动消费者线程
        indexingThread.start();
    }

    private void putTask(Url url) {
        try {
            blockingQueue.put(url);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void test() throws InterruptedException {
        for (int i = 0; i < 500; i++) {
            putTask(new Url("biadu", "mmm", "" + i));
            Thread.sleep(100);
            System.out.println("-----第" + i + "个url插入成功-----");
        }
    }


    static class IndexingThread extends Thread {
        private ArrayBlockingQueue<Url> blockingQueue;

        public IndexingThread(ArrayBlockingQueue<Url> blockingQueue) {
            this.blockingQueue = blockingQueue;
        }

        @Override
        public void run() {
            try {
                // 死循环，从任务队列中取数据进行处理
                while (true) {
                    Url url = blockingQueue.take();
                    this.getHtmlDetail(url);
                    // 分析附件并生成索引
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //模拟获取网页内容
        private void getHtmlDetail(Url url) {
            try {
                // 耗时2分钟
                Thread.sleep(150);
                System.out.println(url.getContent());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("==== 获取网站连接成功 ====");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ArrayBlockingQueueDemo arrayBlockingQueueDemo = new ArrayBlockingQueueDemo();
        arrayBlockingQueueDemo.test();
    }


}
